#!/bin/env python
#coding=utf-8
# 查询/var/log/messages 是否包含 core_pattern 字样
# 0 表示正常  非0异常
import os
import time
import json
import subprocess


def write_file(**kwargs):
    now_core_dict =  kwargs.get('now_core_dict')
    with  open(now_core_dict.get('core_count_file'), "w+") as f:
        reformat = json.dumps(now_core_dict, sort_keys=True, indent=4)
        f.write(reformat)

def read_file(**kwargs):
    now_core_dict =  kwargs.get('now_core_dict')
    with  open(now_core_dict.get('core_count_file'), "r") as f:
        reformat = f.read()
    core_time_count_dict = json.loads(reformat)
    return core_time_count_dict

def get_core_num():
    now_time = int(time.time())
    alarm_time = 24 * 60 * 60
    alarm_flag = 'core_pattern'


    core_count_file = '/tmp/zabbix_core_count'
    log_path = '/var/log/messages'
    # log_path = '/tmp/message'

    log_count = 0
    return_value = 0

    if not os.path.exists(log_path):
        exit(0)

    f = subprocess.Popen(['tail','-n 500',log_path],\
            stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    text = f.stdout.readlines()
    # print text
    for line in text:
        if line.find(alarm_flag) != -1:
            log_count = log_count + 1
    now_core_dict =dict(
        core_count_file = core_count_file,
        core_time = now_time,
        count = log_count
    )

    if not os.path.exists(core_count_file):
        now_core_dict['core_time'] = 0
        write_file(now_core_dict=now_core_dict)
        return_value = 0
    else:
        last_core_dict = read_file(now_core_dict=now_core_dict)
        delta_time = now_time - last_core_dict.get('core_time')
        if  log_count > last_core_dict.get('count'):
            write_file(now_core_dict=now_core_dict)
            return_value = log_count
        elif log_count < last_core_dict.get('count'):
            now_core_dict['count'] = 0
            write_file(now_core_dict=now_core_dict)
            return_value = 0
        elif log_count == last_core_dict.get('count') and delta_time < alarm_time:
            return_value = log_count
    return return_value

def main():
    core_num = get_core_num()
    if not core_num :
        core_num = 0

    prom = '''\
# HELP node_system_corefile 存在core文件
# TYPE node_system_corefile gauge
node_system_corefile{method="log"} %s''' % (core_num)
    return prom


    
if __name__ == '__main__':
    print main()